package com.blinddate.controller;

import com.blinddate.context.BaseContext;
import com.blinddate.pojo.dto.OrdersPaymentDTO;
import com.blinddate.pojo.entity.GoodsType;
import com.blinddate.pojo.entity.Orders;
import com.blinddate.pojo.result.Result;
import com.blinddate.pojo.vo.OrderPaymentVO;
import com.blinddate.service.GoodsTypeService;
import com.blinddate.service.OrdersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.UUID;

@RestController
@RequestMapping("/user/pay")
@Slf4j
@Api(tags = "支付功能功能")
public class PayController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private GoodsTypeService goodsTypeService;


    @PostMapping("/place_order")
    @ApiOperation("下单")
    public Result<Orders> placeOrder(@RequestParam Long GoodsId){//生成订单返回数据给前端
        Orders orders = new Orders();
        log.info("下单,参数orders:{}",orders);
        Long userId = BaseContext.getCurrentId();
        //设置用户id
        orders.setUserId(userId);
        //
        orders.setDescription(userId.toString());
        //通过uuid创建订单号
        orders.setOutTradeNo(String.valueOf((userId+System.currentTimeMillis()/1000)));
        //设置订单状态为未支付
        orders.setStatus(0);
        orders.setOrderTime(LocalDateTime.now());
        GoodsType byId = goodsTypeService.getById(GoodsId);
        orders.setTotal(byId.getTotal());
        orders.setGoodsId(GoodsId);

        boolean save = ordersService.save(orders);

        if (save){
            return Result.success(orders);
        }
        return Result.error("订单生成失败");
    }


    @PutMapping("/payment")
    @ApiOperation("订单支付")
    public Result<OrderPaymentVO> payment(@RequestBody OrdersPaymentDTO ordersPaymentDTO) {//确认支付   将支付用到的数据给予给前端，前端通过微信接口调用微信支付
        log.info("订单支付,参数ordersPaymentDTO:{}",ordersPaymentDTO);
        log.info("订单支付：{}", ordersPaymentDTO);
        OrderPaymentVO orderPaymentVO = ordersService.payment(ordersPaymentDTO);
        log.info("生成预支付交易单：{}", orderPaymentVO);
        return Result.success(orderPaymentVO);
    }
}
